<?php

namespace app\merchant\controller;

use app\common\lib\Constant;
use app\common\lib\MyController;
use app\common\lib\Page;
use app\merchant\model\TpAssets;
use app\merchant\model\TpCredit;
use app\merchant\model\TpActualInvestRepay;
use app\merchant\model\TpAccount;

/**
 * 还款计划 
 * author abao 
 * date 2018-03-01
 */
class Repayment extends MyController
{

    /**
     * 待还款
     * @return type
     */
    public function waitRepayment()
    {
        //调用公共处理方法，1：待还款；2：已还款；3：逾期代偿
        $this->_common(TpActualInvestRepay::STATUS_PAYING);

        return view('Repayment/wait_repayment');
    }

    /**
     * 已还款
     * @return type
     */
    public function haveRepayment()
    {
        //调用公共处理方法，1：待还款；2：已还款；3：逾期代偿
        $this->_common(TpActualInvestRepay::STATUS_PAIED);

        return view('Repayment/have_repayment');
    }

    /**
     * 逾期代偿
     * @return type
     */
    public function overdueCompensation()
    {
        //调用公共处理方法，1：待还款；2：已还款；3：逾期代偿
        $this->_common(TpActualInvestRepay::STATUS_TERMINATE);

        return view('Repayment/overdue_compensation');
    }

    /**
     * 公共处理函数
     * @param type $type int 1：待还款；2：已付款；2：逾期代偿
     * @return boolean
     */
    private function _common($type)
    {
        $user_id = $this->_Uid;

        //搜索条件
        $page = input('page', 1);
        $borrower_name = trim(input('borrower_name', ''));
        $title = input('title', '');
        $repayment_type = input('repayment_type', 0);
        //还款时间
        $planned_repay_time = input('planned_repay_time', 0);
        $planned_repay_time_start = input('planned_repay_time_start', '');
        $planned_repay_time_end = input('planned_repay_time_end', '');
        //扣款时间
        $real_repay_time_start = input('real_repay_time_start', '');
        $real_repay_time_end = input('real_repay_time_end', '');

        $this->assign('borrower_name', $borrower_name);
        $this->assign('title', $title);
        $this->assign('repayment_type', $repayment_type);
        //还款时间
        $this->assign('planned_repay_time_start', $planned_repay_time_start);
        $this->assign('planned_repay_time_end', $planned_repay_time_end);
        //扣款时间
        $this->assign('real_repay_time_start', $real_repay_time_start);
        $this->assign('real_repay_time_end', $real_repay_time_end);

        $where = [];
        //商户
        $where['tbr.merchant'] = ['=', $user_id];
        if ($type == TpActualInvestRepay::STATUS_PAYING) {
            //未还款
            $where['ir.status'] = ['=', TpActualInvestRepay::STATUS_PAYING];
        } elseif ($type == TpActualInvestRepay::STATUS_PAIED) {
            //已还款
            $where['ir.status'] = ['in', [TpActualInvestRepay::STATUS_PAIED, TpActualInvestRepay::STATUS_BEFORE]];
        } elseif ($type == TpActualInvestRepay::STATUS_TERMINATE) {
            //逾期代偿
            $where['ir.status'] = ['in', [TpActualInvestRepay::STATUS_PAIED, TpActualInvestRepay::STATUS_BEFORE]]; //已还款
            //超过还款时间七天以上视为逾期（真实还款时间-计划还款时间大于7天）
            $where['ir.real_repay_time - ir.planned_repay_time'] = ['>', 86400 * 7];
        }

        //借款人
        if ($borrower_name) {
            $where['ap.borrower_name'] = ['like', '%' . $borrower_name . '%'];
        }
        //关联标的
        if ($title) {
            $where['tb.title'] = ['like', '%' . $title . '%'];
        }
        //还款方式
        if ($repayment_type) {
            $where['ap.repayment_type'] = ['=', $repayment_type];
        }

        //扣款时间
        if ($real_repay_time_start && $real_repay_time_end) { //如果两个区间搜索都有值
            $where['ir.planned_repay_time'] = ['BETWEEN', [strtotime($real_repay_time_start), strtotime($real_repay_time_end) + 86400 - 1]];
        } elseif ($real_repay_time_start) { //只有起始值
            $where['ir.planned_repay_time'] = ['>=', strtotime($real_repay_time_start)];
        } elseif ($real_repay_time_end) { //只有结束值
            $where['ir.planned_repay_time'] = ['<', strtotime($real_repay_time_end) + 86400];
        }

        //如果是待付款的
        if ($type == TpActualInvestRepay::STATUS_PAYING) {
            //还款时间
            if ($planned_repay_time) {
                switch ($planned_repay_time) {
                    case 1: //今日应还
                        $time_min = strtotime(date('Ymd'));
                        $time_max = strtotime(date('Ymd')) + 86400 - 1;
                        $where['ir.planned_repay_time'] = ['BETWEEN', [$time_min, $time_max]];
                        break;
                    case 2: //次日应还
                        $time_min = strtotime(date('Ymd')) + 86400;
                        $time_max = strtotime(date('Ymd')) + 86400 * 2 - 1;
                        $where['ir.planned_repay_time'] = ['BETWEEN', [$time_min, $time_max]];
                        break;
                    case 3: //后天应还
                        $time_min = strtotime(date('Ymd')) + 86400 * 2;
                        $time_max = strtotime(date('Ymd')) + 86400 * 3 - 1;
                        $where['ir.planned_repay_time'] = ['BETWEEN', [$time_min, $time_max]];
                        break;
                    case 4: //近七日应还
                        $time_min = strtotime(date('Ymd'));
                        $time_max = strtotime(date('Ymd')) + 86400 * 7 - 1;
                        $where['ir.planned_repay_time'] = ['BETWEEN', [$time_min, $time_max]];
                        break;
                    default:
                        break;
                }
            }
            //还款时间
            if ($planned_repay_time_start && $planned_repay_time_end) { //如果两个区间搜索都有值
                $where['ir.planned_repay_time'] = ['BETWEEN', [strtotime($planned_repay_time_start), strtotime($planned_repay_time_end) + 86400 - 1]];
            } elseif ($planned_repay_time_start) { //只有起始值
                $where['ir.planned_repay_time'] = ['>=', strtotime($planned_repay_time_start)];
            } elseif ($planned_repay_time_end) { //只有结束值
                $where['ir.planned_repay_time'] = ['<', strtotime($planned_repay_time_end) + 86400];
            }
            //如果没有还款时间，就默认为今天
//            if (!$planned_repay_time && !$planned_repay_time_start && !$planned_repay_time_end) {
//                $time_min = strtotime(date('Ymd'));
//                $time_max = strtotime(date('Ymd')) + 86400 - 1;
//                $where['ir.planned_repay_time'] = ['BETWEEN', [$time_min, $time_max]];
//            }
            //总计应还金额
            $total_pay = $this->_getSumMoney($where);
            $this->assign('total_pay', number_format($total_pay, 2));

            //商户可能充值了，充值后金额需要修改的
            $account = TpAccount::where('user_id', '=', $user_id)->field('balance, freeze')->find();
            //同时更新session中的值
            $this->_Account['balance'] = $account['balance'];
            $this->_Account['freeze'] = $account['freeze'];
            //可用金额
            $total = $this->_Account['balance'] + $this->_Account['freeze'];
            $this->assign("total", number_format($total, 2));
            //今日应还金额
            $tody_min = strtotime(date('Ymd'));
            $today_max = strtotime(date('Ymd')) + 86400 - 1;
            $today_where['ir.planned_repay_time'] = ['BETWEEN', [$tody_min, $today_max]];
            //商户
            $today_where['tbr.merchant'] = ['=', $user_id];
            //未还款
            $today_where['ir.status'] = ['=', TpActualInvestRepay::STATUS_PAYING];
            $today_pay = $this->_getSumMoney($today_where);
            $this->assign('today_pay', number_format($today_pay, 2));
        } elseif ($type == TpActualInvestRepay::STATUS_PAIED) {
            //已还款总额
            $total_pay = $this->_getSumMoney($where);
            $this->assign('total_pay', number_format($total_pay, 2));
        } elseif ($type == TpActualInvestRepay::STATUS_TERMINATE) {
            //逾期总额
            $total = $this->_getSumMoney($where);
            $this->assign('total', number_format($total, 2));
        }


        //数量
        $count = TpCredit::alias('tc')
                ->join('tp_borrow tb', 'tb.id = tc.borrow_id')
                ->join('tp_assets_pool ap', 'ap.id = tc.assets_pool_id')
                ->join('tp_borrow_request tbr', 'tbr.id = ap.request_id', 'LEFT')
                ->join('tp_actual_invest_repay ir', 'tc.id = ir.actual_invest_id')
                ->where($where)
                ->group('tc.id')
                ->count('tc.id');
        //列表数据
        $list = TpCredit::alias('tc')
                ->join('tp_user tu', 'tu.uid = tc.investor_uid')
                ->join('tp_borrow tb', 'tb.id = tc.borrow_id')
                ->join('tp_assets_pool ap', 'ap.id = tc.assets_pool_id', 'LEFT')
                ->join('tp_assets ta', 'ap.assets_id = ta.id')
                ->join('tp_borrow_request tbr', 'tbr.id = ap.request_id')
                ->join('tp_actual_invest_repay ir', 'tc.id = ir.actual_invest_id')
                ->where($where)
                ->group('tc.id')
                ->page($page, Constant::PAGE_SIZE_MID)
                ->field('tc.id,tc.create_time,ir.planned_repay_time,ir.real_repay_time,ir.capital,ir.interest,tb.title,ap.duration,ap.repayment_type,ta.interest_rate,ap.amount,ap.borrower_name,tu.real_name')
                ->select();
        foreach ($list as $key => $val) {
            $list[$key]['total'] = number_format($val['capital'] + $val['interest'], 2); //总计应还款金额
            $list[$key]['repayment_type'] = TpAssets::getRepaymentTypeName($val['repayment_type']); //还款方式
        }

        $this->assign('list', $list);

        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MID, $page);
        $this->assign('paginator', $paginator);

        //还款方式
        $repayment_type_list = TpAssets::getRepaymentTypeList();
        $this->assign('repayment_type_list', $repayment_type_list);

        return TRUE;
    }

    /**
     * 统计金额
     * @param type $where
     * @return type
     */
    private function _getSumMoney($where = [])
    {
        /*
        return TpCredit::alias('tc')
                ->join('tp_actual_invest_repay ir', 'tc.id = ir.actual_invest_id')
                ->join('tp_borrow tb', 'tb.id = tc.borrow_id')
                ->join('tp_assets_pool ap', 'ap.id = tc.assets_pool_id', 'LEFT')
                ->join('tp_borrow_request tbr', 'tbr.id = ap.request_id')
                ->where($where)
                ->sum('ir.capital + ir.interest');
        */
        //tp_credit对tp_actual_invest_repay是1对多
        $data =  TpCredit::alias('tc')
                ->join('tp_actual_invest_repay ir', 'tc.id = ir.actual_invest_id')
                ->join('tp_borrow tb', 'tb.id = tc.borrow_id')
                ->join('tp_assets_pool ap', 'ap.id = tc.assets_pool_id', 'LEFT')
                ->join('tp_borrow_request tbr', 'tbr.id = ap.request_id')
                ->where($where)
                ->group('tc.id')
                ->field('ir.capital,ir.interest')
                ->select();
        $capital_sum = array_sum(array_column($data, 'capital'));
        $interest_sum = array_sum(array_column($data, 'interest'));
        $total = $capital_sum + $interest_sum;
        return $total;
    }

    /**
     * 还款计划
     * @return type
     */
    public function getBorrowReplyListAjax()
    {
        $id = input('id');

        $list = TpActualInvestRepay::where('actual_invest_id', '=', $id)->order('sort_order')->select();

        foreach ($list as $key => $val) {
            $list[$key]['status'] = TpActualInvestRepay::getStatusName($val['status']);
            $list[$key]['planned_repay_time'] = date('Y-m-d', $val['planned_repay_time']) . '(' . $val['sort_order'] . ')';
            $list[$key]['total'] = $val['capital'] + $val['interest'];
        }

        return parent::returnData(1, '成功', $list);
    }

}
